import { defineStore } from "pinia";
import { STORE_PREFIX } from "@/utils/constant";
import { SocketIOWrapper } from "@/utils/socket";
import { SocketStatus } from "@/enums";

type SocketIOWrapperType = InstanceType<typeof SocketIOWrapper>;

interface SocketState {
  name: string;
  client: SocketIOWrapperType | null;
  status: SocketStatusType;
}

export const useSocketStore = defineStore({
  id: `${STORE_PREFIX}ws_store`,
  state: (): SocketState => ({
    name: "room",
    // socket wrapper 实例
    client: null,
    // socket 连接状态
    status: SocketStatus.CLOSE
  }),
  actions: {
    setClient(client: SocketIOWrapperType | null) {
      this.client = client as any;
    },
    setStatus(status: SocketStatusType) {
      if (this.status === status) {
        return;
      }
      this.status = status;
    },
    // 初始化Socket
    async initSocket() {
      // check is init
      if (this.client?.isConnected?.()) {
        return;
      }
      const ws = new SocketIOWrapper(useSocketStore(), this.name);
      this.setClient(ws);
    },
    // 关闭Socket连接
    closeSocket() {
      this.client?.close?.();
      this.setClient(null);
    },
    // 断开连接
    disconnect() {
      this.client?.disconnect?.();
    }
  }
});
